package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.ServiceManager;
import com.xyzh05.model.Service;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class ServiceAction extends BaseAction implements Preparable {
    private ServiceManager serviceManager;
    private List services;
    private Service service;
    private Long id;
    private String query;

    public void setServiceManager(ServiceManager serviceManager) {
        this.serviceManager = serviceManager;
    }

    public List getServices() {
        return services;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String serviceId = getRequest().getParameter("service.id");
            if (serviceId != null && !serviceId.equals("")) {
                service = serviceManager.get(new Long(serviceId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        services = serviceManager.search(query, Service.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public String delete() {
        serviceManager.remove(service.getId());
        saveMessage(getText("service.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            service = serviceManager.get(id);
        } else {
            service = new Service();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (service.getId() == null);

        serviceManager.save(service);

        String key = (isNew) ? "service.added" : "service.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}